package net.llz.controller;

import net.llz.config.WeChatConfig;
import net.llz.model.UserDO;
import net.llz.model.VideoOrderDO;
import net.llz.service.UserService;
import net.llz.service.VideoOrderService;
import net.llz.util.JWTUtil;
import net.llz.util.JsonData;
import net.llz.util.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;

@RestController
@RequestMapping("/api/v1/wechat")
public class WeChatController {

    @Autowired
    private WeChatConfig weChatConfig;


    @Autowired
    private UserService userService;

    @Autowired
    private VideoOrderService videoOrderService;
    /**
     * 拼装扫一扫url
     * @param accessPage
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("login_url")
    public JsonData loginUrl(@RequestParam(value = "access_page",required = true) String accessPage) throws UnsupportedEncodingException {
        String redirectUrl = weChatConfig.getOpenRedirectUrl();
        String callbackUrl = URLEncoder.encode(redirectUrl,"GBK");

        String qrcodeUrl= String.format(weChatConfig.getOpenQrcodeUrl(),weChatConfig.getOpenAppid(),callbackUrl,accessPage);
        return JsonData.buildSuccess(qrcodeUrl);
    }

    /**
     * 微信扫码登录，回调地址
     * @param code
     * @param state
     * @param response
     * @throws IOException
     */
    @GetMapping("/user/callback")
    public void wechatUserCallback(@RequestParam(value = "code",required = true) String code,
                                   String state, HttpServletResponse response) throws IOException {


        UserDO userDO = userService.saveWeChatUser(code);
        if(userDO != null){
            //生成jwt
            String token = JWTUtil.geneJsonWebToken(userDO);
            // state 当前用户的页面地址，需要拼接 http://  这样才不会站内跳转

            response.sendRedirect(state+"?token="+token+"&head_img="+userDO.getHeadImg()+"&name="+URLEncoder.encode(userDO.getName(),"UTF-8"));
        //    response.sendRedirect(state+"?token="+token+"&head_img="+userDO.getHeadImg()+"&name="+URLEncoder.encode(userDO.getName(),"UTF-8"));

        }


    }

    /**
     *  微信支付回调
     * @param request
     * @param response
     */
    @PostMapping ("/order/callback")
    public void orderCallback(HttpServletRequest request,HttpServletResponse response) throws Exception {

        InputStream inputStream = request.getInputStream();
        //BufferedReader是包装设计模式，性能更搞

        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
        StringBuffer sb =new StringBuffer();
        String line;
        while ((line=in.readLine())!=null){
            sb.append(line);
        }
        in.close();
        inputStream.close();

        Map<String,String> callbackMap  = WXPayUtil.xmlToMap(sb.toString());
        System.out.println(callbackMap .toString());

        SortedMap<String,String> sortedMap = WXPayUtil.getSortedMap(callbackMap);

        //判断签名是否正确
        if(WXPayUtil.isCorrectSign(sortedMap,weChatConfig.getKey())){
            String outTradeNo = sortedMap.get("out_trade_no");

            VideoOrderDO dbvideoOrderDO = videoOrderService.findByOutTradeNo(outTradeNo);

            if(dbvideoOrderDO != null && dbvideoOrderDO.getState()==0){
                VideoOrderDO videoOrderDO = new VideoOrderDO();
                videoOrderDO.setOpenid(sortedMap.get("openid"));
                videoOrderDO.setOutTradeNo(outTradeNo);
                videoOrderDO.setNotifyTime(new Date());
                videoOrderDO.setState(1);
                int rows = videoOrderService.updateVideoOderByOutTradeNo(videoOrderDO);
                if (rows==1){
                    //通知微信订单处理成功
                    response.setContentType("text/xml");
                    response.getWriter().println("success");
                    return;
                }
            }

        }


    }

}
